package com.jianshuge.app.bean;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;

import java.util.ArrayList;
import java.util.List;

import com.jianshuge.app.AppException;
import com.jianshuge.app.common.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class BookshelfList extends Entity {
	
	public final static int CATALOG_UID_BOOKSHELF = 1;
	public final static int CATALOG_PUB_BOOKSHELF = 2;
	
	private int page_size;
	private int bookshelf_count;
	
	private List<Bookshelf> bookshelf_list = new ArrayList<Bookshelf>();
	
	public int getPageSize() {
		return page_size;
	}
	
	public int getBookshelfCount() {
		return bookshelf_count;
	}
	
	public List<Bookshelf> getBookshelfList() {
		return bookshelf_list;
	}
	
	public static BookshelfList parse(InputStream inputStream, int bookshelf_start) throws IOException, AppException {
		
		BookshelfList my_bookshelf_list = new BookshelfList();
		Bookshelf bookshelf = null;

		String inputStr;
		BufferedReader streamReader = new BufferedReader( new InputStreamReader(inputStream) ); 
	    StringBuilder responseStrBuilder = new StringBuilder();
	    while ((inputStr = streamReader.readLine()) != null)
	        responseStrBuilder.append(inputStr);
	    String strResult = responseStrBuilder.toString();
		
	    int bookshelf_idx = bookshelf_start;
		try {
			JSONArray json_arr = new JSONArray(strResult);
			
			my_bookshelf_list.page_size = json_arr.length();
			my_bookshelf_list.bookshelf_count = json_arr.length();
			
			for (int i = 0; i < json_arr.length() ; i++) {		
				bookshelf = new Bookshelf();
				JSONArray bookshelf_json_arr = json_arr.optJSONArray(i);
				
				if( bookshelf_json_arr == null )
					break;
				
				bookshelf.id = bookshelf_idx;
				
				for (int j = 0; j < bookshelf_json_arr.length(); j++) {
					BooklistItem booklist_item = new BooklistItem();
					JSONObject booklist_item_json_obj = bookshelf_json_arr.optJSONObject(j);
					booklist_item.setBookId( booklist_item_json_obj.optInt("book_id") );
					booklist_item.setTitle( booklist_item_json_obj.getString("book_title") );
					booklist_item.setBookImageUrl( booklist_item_json_obj.getString("book_image_url") );
					booklist_item.setBookRating( booklist_item_json_obj.getString("book_rating") );
					bookshelf.getBooklistItems().add(booklist_item);
				}
				
				my_bookshelf_list.getBookshelfList().add(bookshelf);
				bookshelf_idx++;
				bookshelf = null;
			}
			
		} catch (JSONException e) { 
            System.out.println("Jsons parse error !"); 
            e.printStackTrace(); 
        }
		
		return my_bookshelf_list;
	}
}
